// 这是供给进程
#pragma once

#include <iostream>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <fcntl.h>
#include "Common.hpp"

using namespace std;

class Init
{
public:
    Init()
    {
        umask(0);
        int n = ::mkfifo(gpipeFile.c_str(), gmode);
        if(n < 0)  // mkfifo 失败，会返回-1，并设置错误码
        {
            cerr << "mkfifo failed" << endl;
            return;
        }
        cout << "mkfifo successed" << endl; 
    }
    ~Init()
    {
        int n = ::unlink(gpipeFile.c_str());
        if(n < 0)  // unlink 失败会返回-1,并设置错误码
        {
            cerr << "unlink failed" << endl;
            return;
        }
        cout << "unlink successed" << endl;
    }
};

Init init;

class Server
{
public:
    Server()
        :_fd(gdefaultfd)
    {}

    bool OpenPipeForRead()
    {
        _fd = OpenPipe(gForRead);  // 让发送者只读
        if(_fd < 0)  // open 失败会返回 -1
            return false;
        return true;
    }

    // 接收管道里的信息
    int RecievePipe(string* out)
    {
        char buffer[gsize];
        ssize_t n = ::read(_fd, buffer, sizeof(buffer)-1);
        if(n > 0)  // read 的返回值是实际读取到的字节，如果大于0，就说明读取成功
        {
            buffer[n] = '\0';  // 截断末尾无效字节
            *out = buffer;
        }
        return n;
    }

    void ClosePipe()
    {
        ClosePipeHelper(_fd);
    }

    ~Server()
    {}
private:
    int _fd;
};